package com.example.core.vsvUpload;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName CsvUploadController
 * @Author zhangzhaoyang
 * @Date 2019/10/15 10:57
 **/
@RequestMapping("/upload")
@Slf4j
@RestController
public class CsvUploadController {
    private static Logger logger = LoggerFactory.getLogger(CsvUploadController.class);

    //定义自己的服务类接口
//    @Autowired
//    private Service service;
/**
 * 下载CSV
 */

    @GetMapping("/downloadCSV")
    public String downloadAllUserRoleCSV(HttpServletResponse response) throws IOException {
//        String[] head = service.getHead();
//        List<String[]> values = service.getValues();
//        String fileName = service.getName();

        String[] head = {"head一","head二","head三"};
        List<String[]> values = new ArrayList<String[]>();
        values.add(new String[]{"内容1","内容11","内容111"});
        values.add(new String[]{"内容2","内容22","内容222"});
        values.add(new String[]{"内容3","内容33","内容333"});
        String fileName = "11111111";

        File file = CSVUtils.makeTempCSV(fileName, head, values);
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName +".csv");
        CSVUtils.downloadFile(response, file);
        return null;
    }

    /**
     * @return
     * @Description 上传CSV
     * @Param file
     **/
    @PostMapping(value = "/uploadCSV")
    public String upload(@RequestParam("file") MultipartFile multipartFile) {
        try {
            //上传内容不能为空
            if (multipartFile.isEmpty()) {
                return "500";
            }
            File file = CSVUtils.uploadFile(multipartFile);
            List<List<String>> userRoleLists = CSVUtils.readCSV(file.getPath(), 7);
            System.out.println("解析的csv==:"+userRoleLists.toString());
            for (List<String> ss:userRoleLists){
                System.out.println("解析==:"+ss);
            }
//           解析好的csv文件数据传到service层进行处理
//           service.doSth(userRoleLists);
            file.delete();
            return "200";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "500";
    }

}
